#!/usr/bin/env python

import sys
import string

__author__ = "JoseM Alvarez"
__email__ = "josem.alvarez at josemalvarez dot es"
__version__ = "$Revision: 1.0 $"


def generateBeginFile():
	print "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
	print "<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xml:base=\"http://purl.org/weso/cpv/2008\" xmlns:cpv=\"http://purl.org/weso/cpv/2008#\" xmlns:skos=\"http://www.w3.org/2004/02/skos/core#\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:owl=\"http://www.w3.org/2002/07/owl#\">"

#1- f(PSC)=Top classes Hierarchy
def generateTopConcepts():
	print "<cpv:cpvConcept xmlns:skos=\"http://www.w3.org/2004/02/skos/core#\" rdf:type=\"skos:Concept\"/>"
	print ""
	print "<cpv:cpvConcept rdf:about=\"http://purl.org/weso/cpv/2008#cpv-division\">"
	print "	<skos:prefLabel xml:lang=\"en\">Division</skos:prefLabel>"
	print "	<skos:example>01000000-7</skos:example>"
	print "</cpv:cpvConcept>"

	print "<cpv:cpvConcept rdf:about=\"http://purl.org/weso/cpv/2008#cpv-group\">"
	print "	<skos:prefLabel xml:lang=\"en\">Group</skos:prefLabel>"
	print "	<skos:example>01100000-8</skos:example>"
	print "</cpv:cpvConcept>"


	print "<cpv:cpvConcept rdf:about=\"http://purl.org/weso/cpv/2008#cpv-class\">"
	print "	<skos:prefLabel xml:lang=\"en\">Class</skos:prefLabel>"
	print "	<skos:example>01110000-1</skos:example>"
	print "</cpv:cpvConcept>"

	print "<cpv:cpvConcept rdf:about=\"http://purl.org/weso/cpv/2008#cpv-category\">"
	print "	<skos:prefLabel xml:lang=\"en\">Category</skos:prefLabel>"
	print "	<skos:example>01111000-8</skos:example>"
	print "</cpv:cpvConcept>"

def generateEndFile():
	print "</rdf:RDF>"

#2   f(Id)=Skos-Uri
def formatId(id):
	return "http://purl.org/weso/cpv/2008#" + id 

#4   f(Id)=RDF-type -->
def getType(id):
	type = "http://purl.org/weso/cpv/2008#cpv-category"
	if id[2:8]=="000000":
		type = "http://purl.org/weso/cpv/2008#cpv-division"
	elif id[3:8]=="00000":
		type ="http://purl.org/weso/cpv/2008#cpv-group"
	elif id[4:8]=="0000":
		type = "http://purl.org/weso/cpv/2008#cpv-class"
	return type


#3   f(Id)=Skos-Broader-Classes -->
def getBroader(id, codes):
	broader = ""
	if id[3:8]=="00000":
		broader = generateBroader(id[0:2] + "000000",codes)
	elif id[4:8]=="0000":
		broader = generateBroader(id[0:3] + "00000",codes)
	elif id[5:8]=="000":
		broader = generateBroader(id[0:4] + "0000",codes)
	elif id[6:8]=="00":
		broader = generateBroader(id[0:5] + "000",codes)
	elif id[7:8]=="0":
		broader = generateBroader(id[0:6] + "00",codes)
	return broader


def generateBroader(id,codes):
	for cod in codes:
		if cod.startswith(id):
			return formatId(cod)
	return ""

#2   f(Id)=Skos-Uri
def formatId2003(id):
	return "http://purl.org/weso/cpv/2003#" + id.split("(")[0] 

def generateHistory(oldcodes,t):
	#FIXME: Control digit of ID
	print "<cpv:previousCode rdf:resource=\""+formatId2003(searchIdOld(oldcodes,t[0]))+"\" />"
	print "<skos:changeNote>"+t[1]+"</skos:changeNote>" 	

def createMapTable(mappingsFileName, oldcodes):
	fmappings = open(mappingsFileName)
	mappings = {}
	cod_ant = ""
	for line in fmappings.readlines():
		values = line.split(";")
		cod_current = values[0].replace("\"","")		
		if cod_current == "":
			cod_current = cod_ant
		key = mappings.get(cod_current)
		if len(cod_current) == 7:
			cod_current = "0"+cod_current
		#Search with control digit	
		#id_old = searchIdOld(oldcodes, values[2].replace("\"",""))
		id_old = values[2].replace("\"","")		 		 
		desc_old = values[3].replace("\"","").replace("\n","")
		t = (id_old, desc_old)
		if key is None:
			mappings[cod_current] = [t]
		else:
			mappings[cod_current] += [t]
		cod_ant = cod_current
	return mappings

def searchIdOld(oldcodes,id):
	tid = id	
	for i in range (len(tid),8):
		tid = "0"+tid 
	for cod in oldcodes:
		if cod.startswith(tid):				
			return cod
			
	return ""

def createOldCodesList(oldCodesFileName):
	fp = open(oldCodesFileName)
	oldcodes = []
	for line in fp.readlines():
		oldcodes.append(line.replace("\n",""))
	return oldcodes



def generateCPV(filename,mappingsFileName, oldCodesFileName):
	generateBeginFile()
	generateTopConcepts()
	fp = open(filename)	
	count = 0
	oldcodes = createOldCodesList(oldCodesFileName)
	mappings = createMapTable(mappingsFileName, oldcodes)
	codes = []
	for line in fp.readlines():
		codes.append(line.split(";")[0].replace("\"",""))
	#FIXME: restart read pointer	
	fp.seek(0)
	for line in fp.readlines():
	        if count == 0:
			#"CODE","BG","CS","DA","DE","EL","EN","ES","ET","FI","FR","GA","HU","IT","LT","LV","MT","NL","PL","PT","RO","SK","SL","SV"
			languages=line.split(";") 
			for i in range(len(languages)):
				#Use map function fails with replace map(replace(...),languages)
				languages[i] = languages[i].replace("\"","").replace("\n","")
	        else:  
			values=line.split(";") 
			id = values[0].replace("\"","")
			print "<cpv:cpvConcept rdf:about=\""+formatId(id)+"\">"
			print "<rdf:type>"+getType(id)+"</rdf:type>"
			print "<dc:identifier>"+id+"</dc:identifier>"
			broader = getBroader(id,codes);

			if broader != "":
				print "<skos:broader>"+broader+"</skos:broader>"

			if mappings.get(id.split("-")[0]) != None:
				mappingItems = mappings[id.split("-")[0]]
				for i in range(len(mappingItems)):
					generateHistory(oldcodes, mappingItems[i])
				#map(generateSameAs,mappings[id.split("-")[0]])

			for i in range(len(values)):
				if i >=1:
					if i in range(len(languages)):	
						print "<skos:prefLabel xml:lang=\""+languages[i]+"\">"+values[i].replace("\"","").replace("\n","")+"</skos:prefLabel>"
					else:
						#Warning!!!
						print "<skos:prefLabel>"+values[i].replace("\"","").replace("\n","")+"</skos:prefLabel>"
	
			print "</cpv:cpvConcept>"
        	count = count+1
	generateEndFile()


def usage():
    print 'Usage: python generate-cpv.py <infilename> <mappingsname> <old_codes>'
    sys.exit(-1)

def main():
    args = sys.argv[1:]
    if len(args) != 3:
        usage()
    count = generateCPV(args[0],args[1], args[2])

if __name__ == '__main__':
    main()
